﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WeddingEventManagement_API;
using WeddingEventManagementApp.Models;

namespace WeddingEventManagementApp.Controllers
{
    public class SettingController : BaseController
    {
        ISettingsManager api;
        string ADMIN_ROLE = ApplicationRoles.Administrators.ToString();

        public SettingController()
        {
            if (Roles.IsUserInRole(ADMIN_ROLE))
            {
                api = new SettingsManager();
            }
            else
            {
                RedirectToAction("Index", "Home");
            }
        }

        public ActionResult Index()
        {
            EventManager em = new EventManager();
            var model = new SettingsModel()
            {
                Settings = api.GetSettings().OrderBy(a => a.Group).ThenBy(a => a.Order).ToList(),
                Users = (from MembershipUser u
                            in Membership.GetAllUsers()
                            select new UserModel()
                            {
                                UserName = u.UserName,
                                Email = u.Email,
                                CreatedDate = u.CreationDate,
                                IsAdmin = Roles.IsUserInRole(u.UserName, ApplicationRoles.Administrators.ToString()),
                                LastLoggedIn = u.LastLoginDate
                            }).ToList(),
                EventTypes = em.GetAllEventTypes(),
                Packages = em.GetAllPackages()
            };

            return View("Settings", model);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Index(SettingsModel model)
        {
            foreach (var setting in model.Settings)
            {
                api.SaveSetting(setting);    
            }

            ShowMessage("Settings updated successfully!", MessageType.Success);

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult NewUser(RegisterModel model)
        {
            try
            {
                Membership.CreateUser(model.UserName, model.Password, model.Email);
                return Redirect(Url.Action("Index") + "#tab2");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("RegisterError", e.Message);
            }

            return View(model);
        }

        // Make a User an Administrator
        public ActionResult MakeAdmin(string username)
        {
            if (!Roles.IsUserInRole(username, ADMIN_ROLE))
            {
                Roles.AddUserToRole(username, ADMIN_ROLE);
            }

            return Redirect(Url.Action("Index") + "#tab2");
        }

        // Revoke Administrator Privledges
        public ActionResult RevokeAdmin(string username)
        {
            if (Roles.IsUserInRole(username, ADMIN_ROLE))
            {
                // make sure there is at least one admin
                if (Roles.GetUsersInRole(ADMIN_ROLE).Count() > 1)
                {
                    Roles.RemoveUserFromRole(username, ADMIN_ROLE);
                }
            }

            return Redirect(Url.Action("Index") + "#tab2");
        }

        // Delete User
        public ActionResult DeleteUser(string username)
        {
            Membership.DeleteUser(username, false);

            // if you're deleting yourself, sign out
            if (username == User.Identity.Name)
            {
                FormsAuthentication.SignOut();
            }

            return Redirect(Url.Action("Index") + "#tab2");
        }

        // Create Event Type
        public ActionResult CreateEventType(EventType type)
        {
            try 
	        {
		        new EventManager().CreateEventType(type.EventTypeName, type.CalendarColor);
                return Redirect(Url.Action("Index") + "#tab3");
	        }
	        catch (Exception)
	        {
                throw;
	        }
        }

        // Create Package
        public ActionResult CreatePackage(Package package)
        {
            try
            {
                new EventManager().CreatePackage(package.PackageType, package.BasePrice, package.Description, package.Color);
                return Redirect(Url.Action("Index") + "#tab4");
            }
            catch (Exception)
            {
                throw;
            }
        }

        // Reset User Password
        public string ResetPassword(string username)
        {
            try
            {
                var u = Membership.GetUser(username);
                return string.Format("{0}'s password has been reset to <strong>{1}</strong>", username, u.ResetPassword());
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
